const path = require('path')
const _timesTamp = new Date().getTime()
const webpack = require('webpack')
const isMinimize = ['production', 'pro', 'pre', 'qa'].includes(
	process.env.NODE_ENV
)
// const isPro = ['production', 'pro'].includes(process.env.NODE_ENV)
const _resolve = (dir) => path.join(__dirname, dir)
const SERVICE_ENV = {
	main: process.env.VUE_APP_BaseUrl,
	web: process.env.VUE_APP_BaseUrl,
	cdn: process.env.VUE_APP_CDN,
	WXAuthShare: process.env.VUE_APP_BaseUrl,
	DCAPI: '',
}

module.exports = {
	publicPath: `/BetaCS.CustBindH5`,
	outputDir: 'dist/',
	lintOnSave: true,
	runtimeCompiler: false,
	// 生产环境是否生成 sourceMap 文件
	productionSourceMap: false,
	chainWebpack: (config) => {
		config.resolve.alias
			.set('@', _resolve('src'))
			.set('@C', _resolve('src/components'))
			.set('@IMG', _resolve('src/assets/img'))
			.set('@CSS', _resolve('src/assets/css'))
		// 禁止打包为base64图片
		config.module
			.rule('images')
			.use('url-loader')
			.loader('url-loader')
			.tap((options) => Object.assign(options, { limit: 1024 * 5 }))
		config.module // fixes https://github.com/graphql/graphql-js/issues/1272
			.rule('mjs$')
			.test(/\.mjs$/)
			.include.add(/node_modules/)
			.end()
			.type('javascript/auto')
		config.optimization.minimize(isMinimize)
		config.plugins.delete('prefetch')
	},
	configureWebpack: (config) => {
		const pluginsPro = [
			new webpack.DefinePlugin({
				'process.env.SERVERS_ENV': JSON.stringify(SERVICE_ENV),
			}),
		]
		const outputPro = {
			// 输出重构  打包编译后的 文件名称  【模块名称.时间戳】
			filename: `js/[name].${_timesTamp}.js`,
			chunkFilename: `js/[name].${_timesTamp}.js`,
		}
		config.output = Object.assign(config.output, outputPro)
		config.plugins = [...config.plugins, ...pluginsPro]
		config.devtool = isMinimize ? false : 'cheap-module-eval-source-map' // 取消主站webpack源码
		config.module.rules.push({
			test: /\.mjs$/,
			include: /node_modules/,
			type: 'javascript/auto',
		})
	},
	css: {
		// 开启 CSS source maps?
		sourceMap: false,
		loaderOptions: {
			less: {
				javascriptEnabled: true,
			},
		},
	},
	devServer: {
		disableHostCheck: true,
		inline: true,
		hot: true,
		port: 8080,
		publicPath: '/BetaCS.CustBindH5',
		headers: {
			'Access-Control-Allow-Origin': '*',
		},
		proxy: {
			'^/(?!BetaCS.CustBindH5)': {
				target: 'https://w-1.test.betawm.com/',
				ws: true,
				changeOrigin: true,
				pathRewrite: {},
				onProxyReq(proxyReq, req, res, options) {
					proxyReq.removeHeader('origin')
				},
			},
		},
		before: require('./src/mock/index.js'),
	},
}
